//
//  SFCrypto.m
//  SFast
//
//  Created by TrendyFeng on 15/11/25.
//  Copyright © 2015年 TrendyFeng. All rights reserved.
//

#import "SFCrypto.h"
#import "commoncrypto/commondigest.h"
#include <openssl/pem.h>
#include <openssl/rsa.h>
@implementation SFCrypto

+ (NSString *)encodeByPublicKey:(NSString*)pubKey message:(NSString *)inputText{
    
    NSString *newPubKey = @"";
    int count = (int)[pubKey length] / 64;
    for (int i = 0 ; i <= count ; i++){
        NSString *tmpString = [pubKey substringWithRange:NSMakeRange(i * 64, (i == count ? (int)[pubKey length] % 64 : 64))];
        newPubKey = [newPubKey stringByAppendingFormat:@"\n%@",tmpString];
    }
    
    pubKey = [@"-----BEGIN PUBLIC KEY-----\n" stringByAppendingString:newPubKey];
    
    if (![pubKey hasSuffix:@"\n"]) {
        pubKey = [pubKey stringByAppendingString:@"\n"];
    }
    
    pubKey = [pubKey stringByAppendingString:@"-----END PUBLIC KEY-----\n"];
    
    unsigned char encrypted[1024];
    bzero(encrypted, sizeof(encrypted));
    
    BIO *bio = NULL;
    RSA *rsa2 = NULL;
    
    bio = BIO_new_mem_buf((char*)[pubKey UTF8String], -1);
    if (bio == NULL){
        printf("Pub_Key Read Failure!!\n");
    }
    rsa2 = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, NULL);
    if (!rsa2){
        printf("Pub_Key Read Failure!!\n");
    }
    
    NSData *contentData = [inputText dataUsingEncoding:NSASCIIStringEncoding];
    NSInteger contentLen = [contentData length];
    unsigned char from[contentLen];
    bzero(from, sizeof(from));
    memcpy(from, [contentData bytes], contentLen);
    
    int state = RSA_public_encrypt ((int)contentLen, from, encrypted, rsa2, RSA_PKCS1_PADDING);
    if( state == -1 ){
        printf("Encrypt Failed!!\n");
        return @"";
    }
    
    NSString *encryptedTxt = @"";
    for (int i = 0; i < 128; i++) {
        encryptedTxt = [encryptedTxt stringByAppendingFormat:@"%02x",encrypted[i]];
    }
   
    //printf("\n| encryptedTxt = %s",[encryptedTxt UTF8String]);
   
    return encryptedTxt;
}

+ (NSString *)encodeMD5:(NSString *)inputText
{
    const char *cStr = [inputText UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
    
}


@end
